<template>
  <div>
    <BottomDrawer
      :visible="addVisible"
      :title="'获取'"
      :width="516"
      @close="addVisible = false"
    >
      <div>
        <el-row>
          <el-col :span="22" :offset="1">
            <PageForm
              ref="pageForm"
              :list="list"
              :form-data="formData"
              :rules="rules"
            >
            </PageForm>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="addVisible = false">取 消</el-button>
      </template>
    </BottomDrawer>
  </div>
</template>

<script setup lang="ts">
import type { FormRules } from 'element-plus';
import { pullTemplate, getGroupSelectList } from '@/api/formwork/index';

const rules = reactive<FormRules<any>>({
  groupId: [{ required: true, message: '请选择个人目录', trigger: 'change' }],
});

const emits = defineEmits(['refresh']);
const pageForm = ref();
const directory = ref<any[]>([]);

defineExpose<{
  open1: (data: any) => void;
}>({
  open1: async (data: any) => {
    addVisible.value = true;
    formData.value = data;
    formData.value.groupId = null;
    const res = await getGroupSelectList(data);
    if (res.code == '200') {
      directory.value = res.data.map((item: any) => ({
        ...item,
        label: item.groupName,
        value: item.groupId,
      }));
    }
  },
});

const addVisible = ref(false);

const formData = ref<any>({
  templateName: '',
  templateCategory: '',
  templateType: '',
  groupId: null,
  doctorAdvice: '',
  recomScene: '',
  fieldList: [],
});

const list: any = computed(() => [
  {
    list: [
      {
        span: 24,
        label: '个人目录',
        prop: 'groupId',
        labelWidth: '80px',
        componentProps: { placeholder: '请输入个人目录', width: '362' },
        component: 'select',
        get selectGroupOptions() {
          return directory.value;
        },
      },
    ],
  },
]);

const addDepApi = async () => {
  if (!formData.value.templateId) {
    ElMessage({ type: 'warning', message: '请选中模板', duration: 2000 });
    return;
  }
  pullTemplate(formData.value)
    .then((res) => {
      if (res.code !== '200') {
        ElMessage({ type: 'error', message: res?.msg || '添加失败' , duration: 2000 });
        return;
      }
      ElMessage({ type: 'success', message: '移动成功', duration: 2000 });
      emits('refresh');
      addVisible.value = false;
    })
    .catch((error) => {
      //console.error('添加失败:', error);
    });
};

const handleSubmit = async () => {
  const ruleFormRef = pageForm.value?.ruleFormRef;
  await ruleFormRef.validate((valid: any, fields: any) => {
    if (valid) {
      addDepApi();
    } else {
      //console.log('error submit!', fields);
    }
  });
};
</script>

<style lang="scss" scoped>
.tree-box {
  border: 2px solid #e1e1e1;
  height: 300px;
  width: 451px;
  margin-top: 10px;
  overflow-y: auto;
}
</style>
